package com.example.noteandroid.ui.canvas

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.music.note_android.R
import kotlin.math.roundToInt

/**
 * 颜色选择器对话框
 * 支持预设颜色选择和自定义HSV颜色调节
 */
class ColorPickerDialog(
    context: Context,
    private val initialColor: Int = Color.BLACK,
    private val onColorSelected: (Int) -> Unit
) : Dialog(context) {

    // UI组件
    private lateinit var rvPresetColors: RecyclerView
    private lateinit var seekbarHue: SeekBar
    private lateinit var seekbarSaturation: SeekBar
    private lateinit var seekbarBrightness: SeekBar
    private lateinit var seekbarAlpha: SeekBar
    private lateinit var tvHueValue: TextView
    private lateinit var tvSaturationValue: TextView
    private lateinit var tvBrightnessValue: TextView
    private lateinit var tvAlphaValue: TextView
    private lateinit var colorPreview: View
    private lateinit var tvHexColor: TextView
    private lateinit var tvRgbColor: TextView
    private lateinit var btnCancel: Button
    private lateinit var btnConfirm: Button

    // 颜色状态
    private var currentColor: Int = initialColor
    private val hsv = FloatArray(3)
    private var alpha: Int = 255

    // 预设颜色适配器
    private lateinit var presetColorAdapter: PresetColorAdapter

    // 预设颜色列表
    private val presetColors = listOf(
        Color.BLACK, Color.DKGRAY, Color.GRAY, Color.LTGRAY, Color.WHITE,
        Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN, Color.MAGENTA,
        Color.parseColor("#FF5722"), // Deep Orange
        Color.parseColor("#FF9800"), // Orange
        Color.parseColor("#FFC107"), // Amber
        Color.parseColor("#FFEB3B"), // Yellow
        Color.parseColor("#CDDC39"), // Lime
        Color.parseColor("#8BC34A"), // Light Green
        Color.parseColor("#4CAF50"), // Green
        Color.parseColor("#009688"), // Teal
        Color.parseColor("#00BCD4"), // Cyan
        Color.parseColor("#03A9F4"), // Light Blue
        Color.parseColor("#2196F3"), // Blue
        Color.parseColor("#3F51B5"), // Indigo
        Color.parseColor("#673AB7"), // Deep Purple
        Color.parseColor("#9C27B0"), // Purple
        Color.parseColor("#E91E63"), // Pink
        Color.parseColor("#F44336"), // Red
        Color.parseColor("#795548"), // Brown
        Color.parseColor("#607D8B")  // Blue Grey
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_color_picker)
        
        initViews()
        setupPresetColors()
        setupColorSliders()
        setupButtons()
        
        // 初始化颜色
        setInitialColor(initialColor)
    }

    private fun initViews() {
        rvPresetColors = findViewById(R.id.rv_preset_colors)
        seekbarHue = findViewById(R.id.seekbar_hue)
        seekbarSaturation = findViewById(R.id.seekbar_saturation)
        seekbarBrightness = findViewById(R.id.seekbar_brightness)
        seekbarAlpha = findViewById(R.id.seekbar_alpha)
        tvHueValue = findViewById(R.id.tv_hue_value)
        tvSaturationValue = findViewById(R.id.tv_saturation_value)
        tvBrightnessValue = findViewById(R.id.tv_brightness_value)
        tvAlphaValue = findViewById(R.id.tv_alpha_value)
        colorPreview = findViewById(R.id.color_preview)
        tvHexColor = findViewById(R.id.tv_hex_color)
        tvRgbColor = findViewById(R.id.tv_rgb_color)
        btnCancel = findViewById(R.id.btn_cancel)
        btnConfirm = findViewById(R.id.btn_confirm)
    }

    private fun setupPresetColors() {
        presetColorAdapter = PresetColorAdapter(presetColors) { color ->
            setColor(color)
        }
        rvPresetColors.layoutManager = GridLayoutManager(context, 5)
        rvPresetColors.adapter = presetColorAdapter
    }

    private fun setupColorSliders() {
        // 色相滑块
        seekbarHue.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    hsv[0] = progress.toFloat()
                    updateColorFromHSV()
                    tvHueValue.text = "${progress}°"
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 饱和度滑块
        seekbarSaturation.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    hsv[1] = progress / 100f
                    updateColorFromHSV()
                    tvSaturationValue.text = "${progress}%"
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 明度滑块
        seekbarBrightness.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    hsv[2] = progress / 100f
                    updateColorFromHSV()
                    tvBrightnessValue.text = "${progress}%"
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 透明度滑块
        seekbarAlpha.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    alpha = (progress * 255 / 100f).roundToInt()
                    updateColorFromHSV()
                    tvAlphaValue.text = "${progress}%"
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    private fun setupButtons() {
        btnCancel.setOnClickListener {
            dismiss()
        }

        btnConfirm.setOnClickListener {
            onColorSelected(currentColor)
            dismiss()
        }
    }

    private fun setInitialColor(color: Int) {
        setColor(color)
    }

    private fun setColor(color: Int) {
        currentColor = color
        alpha = Color.alpha(color)
        
        // 转换为HSV
        Color.colorToHSV(color, hsv)
        
        // 更新滑块
        seekbarHue.progress = hsv[0].roundToInt()
        seekbarSaturation.progress = (hsv[1] * 100).roundToInt()
        seekbarBrightness.progress = (hsv[2] * 100).roundToInt()
        seekbarAlpha.progress = (alpha * 100 / 255f).roundToInt()
        
        // 更新显示
        updateColorDisplay()
        updatePresetSelection(color)
    }

    private fun updateColorFromHSV() {
        val rgb = Color.HSVToColor(hsv)
        currentColor = Color.argb(alpha, Color.red(rgb), Color.green(rgb), Color.blue(rgb))
        updateColorDisplay()
        updatePresetSelection(currentColor)
    }

    private fun updateColorDisplay() {
        // 更新预览
        colorPreview.setBackgroundColor(currentColor)
        
        // 更新颜色值显示
        tvHexColor.text = String.format("#%08X", currentColor)
        tvRgbColor.text = String.format(
            "RGB(%d, %d, %d)",
            Color.red(currentColor),
            Color.green(currentColor),
            Color.blue(currentColor)
        )
    }

    private fun updatePresetSelection(color: Int) {
        presetColorAdapter.setSelectedColor(color)
    }

    /**
     * 预设颜色适配器
     */
    private class PresetColorAdapter(
        private val colors: List<Int>,
        private val onColorClick: (Int) -> Unit
    ) : RecyclerView.Adapter<PresetColorAdapter.ColorViewHolder>() {

        private var selectedColor: Int = Color.TRANSPARENT

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ColorViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_color_preset, parent, false)
            return ColorViewHolder(view)
        }

        override fun onBindViewHolder(holder: ColorViewHolder, position: Int) {
            val color = colors[position]
            holder.bind(color, color == selectedColor) {
                onColorClick(color)
            }
        }

        override fun getItemCount(): Int = colors.size

        fun setSelectedColor(color: Int) {
            val oldSelected = selectedColor
            selectedColor = color
            
            // 更新旧选中项和新选中项
            colors.indexOf(oldSelected).takeIf { it >= 0 }?.let { notifyItemChanged(it) }
            colors.indexOf(selectedColor).takeIf { it >= 0 }?.let { notifyItemChanged(it) }
        }

        class ColorViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val colorCircle: View = itemView.findViewById(R.id.color_circle)
            private val selectedIndicator: View = itemView.findViewById(R.id.selected_indicator)

            fun bind(color: Int, isSelected: Boolean, onClick: () -> Unit) {
                colorCircle.setBackgroundColor(color)
                selectedIndicator.visibility = if (isSelected) View.VISIBLE else View.GONE
                itemView.setOnClickListener { onClick() }
            }
        }
    }
}